<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>DenseCap results browser</title>
    <script src="utils.js"></script>
    <script src="jquery-1.8.3.min.js"></script>
    <script src="d3.min.js" charset="utf-8"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    
    <script type="application/javascript">

    var BOX_WIDTH = 8;
    var INPUT_JSON_PATH = 'data/results.json'
    var input_struct = null; // will be loaded from json
    var current_id = 0; // currently shown image id

    // render flags utils
    var render_flags = {
      detections_to_show: 10,
      captions_inline: false,
    }
    function updateCounter(name, d) {
      render_flags[name] += d;
      renderAnnotations();
    }
    function toggleFlag(name) {
      render_flags[name] = !render_flags[name];
      renderAnnotations();
    }

    function getUrlParam(name, fallback) {
      name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
      var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
      if (results === null) return fallback;
      return decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    function loadData() {
      var data_dir = getUrlParam('data_dir', 'data');
      var input_json_path = data_dir + '/results.json';
      var pathmod = input_json_path + '?sigh=' + Math.floor(Math.random() * 100000); // prevent caching
      $.getJSON(pathmod, function(data) {
        input_struct = data; // store in global
        renderImage();
      });
    }

    function updateImg(d) {
      current_id += d;
      current_id = Math.max(0,Math.min(input_struct.results.length-1, current_id)) // clamp
      renderImage();
    }

    var svgg = null; // g element inside svg that contains the annotations
    var desc_div = null; // element to render captions into
    function renderImage() {
      var data_dir = getUrlParam('data_dir', 'data');
      var fname = data_dir + '/' + input_struct.results[current_id].img_name;
      console.log('loading image: ' + fname);

      $("#counterdiv").html('image ' + (current_id+1) + '/' + input_struct.results.length);

      $("#image_vis").html(''); // reset area
      var div = d3.select("#image_vis").append("div").classed('dcent', true);
      
      var img = new Image();
      img.src = fname;
      img.onload = function() {
        var width = this.width;
        var height = this.height;

        // create main rendering elements
        var svg = div.append("svg");
        desc_div = div.append("div").classed('djust', true);
        
        // render the raw image
        var svg_img = svg.append("image").attr("x",0).attr("y",0);
        svg_img.attr('height', height).attr('width', width).attr('xlink:href', fname);
        svg.attr('height', height);
        svg.attr('width', width);

        svgg = svg.append('g');
        renderAnnotations();
      }
    }

    // render just the annotations, leave the image untouched and loaded
    function renderAnnotations() {
      var elt = svgg; // render into g element of svg
      elt.html(''); // flush contents of annotations <g> element
      var delt = desc_div; // description element
      delt.html('');

      var result = input_struct.results[current_id];

      // Render top detections
      var ixscore = [];
      for (var i = 0; i < result.scores.length; i++) {
        ixscore.push([i, result.scores[i]]);
      }
      ixscore.sort(function(a, b) {
        return b[1] - a[1];
      });

      // lets render!
      var nshow = Math.min(render_flags.detections_to_show, result.captions.length);
      for (var k = 0; k < nshow; k++) {
        var i = ixscore[k][0];
        var det_box = result.boxes[i];
        var caption = result.captions[i];
        // render box
        var color = WAD_COLORS[k % WAD_COLORS.length];
        renderBox(elt, det_box, color, BOX_WIDTH, render_flags.captions_inline ? caption : '');
        // render caption in a separate div below the image
        delt.append('span').classed('ddesc', true).style('color', color).html(escapeHtml(caption) + '. ');
      }
    }

    // bind keys to controls
    document.onkeydown = function(e) {
      // d=68, a=65, w=87, s=83, t=84
      if (e.keyCode == 68) updateImg(1);
      if (e.keyCode == 65) updateImg(-1);
      if (e.keyCode == 83) updateCounter('detections_to_show', -1);
      if (e.keyCode == 87) updateCounter('detections_to_show', 1);
      if (e.keyCode == 84) toggleFlag('captions_inline');
      if (e.keyCode == 82) jumpRandom();
    };

    // "int main" function here
    function intmain() {
      loadData();
    }

    function jumpRandom() {
      current_id = Math.floor(Math.random()*(input_struct.results.length-1));
      renderImage();
    }

    </script>
  </head>
  <body onload="intmain()">
    <div id="wrap">

      <div id="header"><h1>DenseCap results browser</h1></div>
      <div id="infodiv">Browse the results using the WSAD hotkeys (A,D: prev/next image, W/S: more/less detections)</div>
      <hr>

      <div id="image_vis"></div>
      <div id="image_vis_controls">
        <button onclick="updateCounter('detections_to_show', -1)" class="bb">Fewer detections (s)</button>
        <button onclick="updateCounter('detections_to_show', 1)" class="bb">More detections (w)</button>
        <button onclick="updateImg(-1)" class="bb">Prev img (a)</button>
        <button onclick="updateImg(1)" class="bb">Next img (d)</button>
        <br>
        <button onclick="toggleFlag('captions_inline')" class="bb" style="width:200px">
          Toggle show captions inline (t)
        </button>
        <button onclick="jumpRandom()" class="bb" style="width:200px">
          Jump to random image (r)
        </button>
      </div>
      <div id="counterdiv" style="text-align:center; font-size:20px; margin-bottom:20px;">

      </div>

    </div>
  </body>
</html>
